<template>
  <a-modal
    v-model:open="modalVisible"
    :title="isEdit ? '编辑系统' : '添加系统'"
    :confirm-loading="loading"
    :width="600"
    :maskClosable="false"
    :footer="null"
  >
    <a-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      layout="horizontal"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 16 }"
    >
      <a-form-item label="应用编码" name="code">
        <a-input
          v-model:value="formData.code"
          placeholder="请输入应用编码（唯一标识）"
          :disabled="isEdit"
        />
      </a-form-item>

      <a-form-item label="应用名称" name="name">
        <a-input v-model:value="formData.name" placeholder="请输入应用名称" />
      </a-form-item>

      <a-form-item label="排序值" name="sort">
        <a-input-number
          v-model:value="formData.sort"
          placeholder="请输入排序值"
          :min="0"
          :max="9999999"
          style="width: 100%"
        />
      </a-form-item>

      <a-form-item label="应用负责人" name="ownerId">
        <a-select
          v-model:value="formData.ownerId"
          placeholder="请选择应用负责人"
          show-search
          :filter-option="filterOption"
        >
          <a-select-option
            v-for="user in userList"
            :key="user.id"
            :value="user.id"
          >
            {{ user.name }} ({{ user.id }})
          </a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="备注" name="remark">
        <a-textarea
          v-model:value="formData.remark"
          placeholder="请输入备注信息"
          :rows="3"
        />
      </a-form-item>
    </a-form>
    <div class="form-footer">
      <a-button class="cancel-btn" @click="handleCancel">取消</a-button>
      <a-button
        type="primary"
        class="submit-btn"
        :loading="loading"
        @click="handleSubmit"
        >保存</a-button
      >
    </div>
  </a-modal>
</template>

<script setup>
import { ref, reactive, computed, watch, onMounted } from "vue";
import { message } from "ant-design-vue";
import { createApplication, updateApplication } from "@/api/application";

import { getEmployeeList } from "@/api/employee";

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  applicationData: {
    type: Object,
    default: null,
  },
  isEdit: {
    type: Boolean,
    default: false,
  },
});

const emit = defineEmits(["update:visible", "success"]);

const formRef = ref();
const userList = ref([]);
const loading = ref(false);

// 处理 visible 的双向绑定
const modalVisible = computed({
  get: () => props.visible,
  set: (value) => emit("update:visible", value),
});

// 表单数据
const formData = reactive({
  code: "",
  name: "",
  sort: 1,
  ownerId: undefined,
  remark: "",
});

// 表单验证规则
const rules = {
  code: [
    { required: true, message: "请输入系统编码", trigger: "blur" },
    {
      pattern: /^[a-zA-Z][a-zA-Z0-9_]*$/,
      message: "系统编码只能包含字母、数字和下划线，且以字母开头",
      trigger: "blur",
    },
  ],
  name: [
    { required: true, message: "请输入系统名称", trigger: "blur" },
    { max: 100, message: "系统名称不能超过100个字符", trigger: "blur" },
  ],
  sort: [
    { required: true, message: "请输入排序值", trigger: "blur" },
    { type: "number", min: 0, message: "排序值不能小于0", trigger: "blur" },
  ],
  ownerId: [{ required: true, message: "请选择系统负责人", trigger: "change" }],
  remark: [{ max: 255, message: "备注不能超过255个字符", trigger: "blur" }],
};

// 用户搜索过滤
const filterOption = (input, option) => {
  const user = userList.value.find((u) => u.id === option.value);
  if (!user) return false;
  return (
    user.name.toLowerCase().includes(input.toLowerCase()) ||
    user.username.toLowerCase().includes(input.toLowerCase())
  );
};

// 获取用户列表
const fetchUserList = async () => {
  try {
    const response = await getEmployeeList();
    // 根据实际API响应结构调整数据解析
    if (response.data) {
      userList.value = response.data.items || response.data || [];
    }
  } catch (error) {
    message.error("获取用户列表失败");
  }
};

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    code: "",
    name: "",
    sort: 0,
    ownerId: undefined,
    remark: "",
  });
  formRef.value?.clearValidate();
};

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate();
    loading.value = true;

    if (props.isEdit) {
      await updateApplication(props.applicationData.id, formData);
      message.success("更新系统成功");
    } else {
      await createApplication(formData);
      message.success("创建系统成功");
    }

    emit("success");
  } catch (error) {
    if (error.errorFields) {
      message.error("请检查表单输入");
    } else {
      message.error(props.isEdit ? "更新系统失败" : "创建系统失败");
    }
  } finally {
    loading.value = false;
  }
};

// 取消操作
const handleCancel = () => {
  emit("update:visible", false);
};

// 监听弹窗显示状态
watch(
  () => props.visible,
  (newVal) => {
    if (newVal) {
      if (props.isEdit && props.applicationData) {
        // 编辑模式，填充数据
        Object.assign(formData, {
          code: props.applicationData.code,
          name: props.applicationData.name,
          status: props.applicationData.status,
          sort: props.applicationData.sort,
          ownerId: props.applicationData.ownerId,
          remark: props.applicationData.remark,
        });
      } else {
        // 新增模式，重置表单
        resetForm();
      }
    }
  }
);

// 初始化
onMounted(() => {
  fetchUserList();
});
</script>

<style scoped>
.form-footer {
  display: flex;
  justify-content: center;
  margin-top: 24px;
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;

  .cancel-btn {
    margin-right: 16px;
    min-width: 80px;
  }

  .submit-btn {
    min-width: 80px;
  }
}
</style>
